import os
import sys
import time
import zipfile
import paramiko
import uuid
import xlrd
import time
import smtplib


class SSHConnection(object):
    # 连接服务器，并将信息保存至内存中
    def __init__(self, host='23.99.103.160', port=22, username='hruser', pwd='Hr~!123456'):
        self.host = host
        self.port = port
        self.username = username
        self.pwd = pwd
        self.__k = None

    def run(self):
        self.connect()
        pass
        self.close()

    def connect(self):
        transport = paramiko.Transport((self.host, self.port))
        transport.connect(username=self.username, password=self.pwd)
        self.__transport = transport

    def close(self):
        self.__transport.close()

    def cmd(self, command):
        ssh = paramiko.SSHClient()
        ssh._transport = self.__transport
        # 执行命令
        stdin, stdout, stderr = ssh.exec_command(command)
        # 获取命令结果
        result = stdout.read()
        return result

    # 创建上传下载函数
    def upload(self, local_path, target_path):
        # 连接，上传
        sftp = paramiko.SFTPClient.from_transport(self.__transport)
        # 将location.py 上传至服务器 /tmp/test.py
        # sftp.put('fort-KEY.py', target_path)
        sftp.put(local_path, target_path)


# sftp.get('')


def getFilesNum(distPath):
    count = 0
    for item in os.listdir(distPath):
        if item.find("xls") != -1 or item.find("xlsx") != -1:
            count += 1
    return count


def renameAll(distPath):
    indexXls = 0
    os.chdir(distPath)
    for item in os.listdir(distPath):
        if item.find("xls") != -1 or item.find("xlsx") != -1:
            formatStr = "X%d." + item.split(".")[1]
            print("formatStr " + formatStr)
            os.rename(item, formatStr % indexXls)
            indexXls += 1


def zipAllFiles(distPath):
    compression = zipfile.ZIP_DEFLATED
    try:
        import zlib
        compression = zipfile.ZIP_DEFLATED
    except:
        compression = zipfile.ZIP_STORED
    path = distPath
    start = path.rfind(os.sep) + 1
    filename = "SYCM_" + time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime(time.time())) + ".zip"  # 'my.zip'
    z = zipfile.ZipFile(filename, mode="w", compression=compression)
    try:
        for dirpath, dirs, files in os.walk(path):
            for file in files:
                z_path = os.path.join(dirpath, file)
                if z_path.find("xls") != -1 or z_path.find("xlsx") != -1:
                    z.write(z_path, file)
                    os.remove(z_path)
        z.close()
    except:
        if z:
            z.close()
    return filename


def uploadToServer(local_path, target_path,num):
    print("uploadToServer")
    ssh = SSHConnection()
    ssh.connect()
    r1 = ssh.cmd('df')
    print(r1)
    # 将文件sftp
    ssh.upload(local_path, target_path)
    # 关闭连接
    ssh.close()
    for i in range(1):  # 发送1封，上面的列表是几个人，这个就填几
        if send_mail(mailto_list,num,
                     time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime(time.time())),"Upload files successfully"):  # 邮件主题和邮件内容
            print
            "done!"
        else:
            print
            "failed!"

def main(distPath):
    import traceback
    try:
        print("distPath is: " + distPath)
        num = getFilesNum(distPath)
        if num >= 103:
            # renameAll(distPath)
            localpath = zipAllFiles(distPath)
            print("localpath is: " + localpath)
            uploadToServer(localpath, "/offer/" + localpath,num)
        else:
            print("file num is not enough!\n")
            send_mail(mailto_list,num,
                     time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime(time.time())),"You have not downloaded entire files");
        # time.sleep(1)
        # main(distPath)
    except:
        print("except in main")
        traceback.print_exc()


def getpath():
    data = xlrd.open_workbook("Path_configuration.xlsx")
    table = data.sheet_by_name(u'Sheet1')
    path = table.cell(0, 1).value
    print("path " + path)
    return path


from email.mime.text import MIMEText

mailto_list = ['rwathena@163.com']  # receiver
mail_host = "smtp.cioadvisory.top"  #
mail_user = "accountchangereadiness@cioadvisory.top"  #
mail_pass = "Accountcr@2016"  #
mail_postfix = "Aldi.com.cn"


def send_mail(to_list, conent1, content2,title):
    print("num "+str(conent1))
    me = "hello" + "<" + mail_user + "@" + mail_postfix + ">"
    msg = MIMEText("Upload " + str(conent1) + " files at " + content2, _subtype='plain')
    msg['Subject'] = title
    msg['From'] = me
    msg['To'] = ";".join(to_list)  #
    try:
        server = smtplib.SMTP()
        server.connect(mail_host)  # 连接服务器
        server.login(mail_user, mail_pass)  # 登录操作
        server.sendmail(me, to_list, msg.as_string())
        server.close()
        return True
    except:
        print("except in sendemail")
        return False


distPath = getpath()  # "G:/test/watching/Allfiles" #os.getcwd()+"\\Allfiles"
main(distPath)

